package tools_util;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;


import android.os.Handler;
import android.os.Message;

public class GetJsonStringFromWeb {

	public static void getJsonString(final String path,
			final JsonCallBack jsonCallBack) {
		final Handler handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				jsonCallBack.getjsonCallBack((String) msg.obj);
			}
		};

		new Thread(new Runnable() {

			@Override
			public void run() {
				HttpURLConnection conn = null;
				InputStream in = null;
				OutputStream out = null;
				byte[] data = null;
				byte[] res = null;
				try {
					data = (path.substring(path.indexOf("?") + 1)).getBytes();
					conn = (HttpURLConnection) new URL(path).openConnection();
					conn.setRequestMethod("POST");
					conn.setConnectTimeout(50000);
					conn.setDoInput(true);
					conn.setDoOutput(true);
					conn.addRequestProperty("Content-Type",
							"application/x-www-form-urlencoded");
					out = conn.getOutputStream();
					out.write(data);
					out.flush();
					conn.connect();
					if (conn.getResponseCode() == 200) {
						in = conn.getInputStream();
						res = StreamTools.read(in);
						String resultString = new String(res, 0, res.length);
						System.out.println("()()()" + resultString);
						Message msg = Message.obtain();
						msg.obj = resultString;
						handler.sendMessage(msg);
					}
				} catch (MalformedURLException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				} finally {
					if (in != null) {
						try {
							in.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
					if (conn != null) {
						conn.disconnect();
					}
				}
			}
		}).start();
	}

	public interface JsonCallBack {
		public void getjsonCallBack(String json);
	}
}
